from django.db import transaction
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response

from rest_framework import status
from .serializers import *
from .models import *
from .filters import *
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from utils.CustomPageNumberPagination import CustomPageNumberPagination
from django.db.models import F
from .Menus import Menus
from user.serializers import UserSeralizer

from user.Login import LoginUserInfoView
import logging

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
logger = logging.getLogger('django')


class SystemMenViewSet(viewsets.ModelViewSet):
    '''
    系统菜单视图级
    '''
    queryset = SystemMen.objects.all().order_by(F('orderNum').asc())  # 强制按照 id 升序排序
    serializer_class = SystemMenSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = SystemMenFilter
    ordering_fields = ['menuId']
    # pagination_class = CustomPageNumberPagination



class SysLoginInfoViewSet(viewsets.ModelViewSet):
    '''
    登录日志视图级
    '''
    queryset = SysLoginInfo.objects.all().order_by(F('info_id').desc())  # 强制按照 id 升序排序
    serializer_class = SysLoginInfoSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = SysLoginInfoFilter
    ordering_fields = ['info_id']
    pagination_class = CustomPageNumberPagination


class SysOperLogViewSet(viewsets.ModelViewSet):
    '''
    操作日志视图级
    '''
    queryset = SysOperLog.objects.all().order_by(F('oper_id').desc())  # 强制按照 id 升序排序
    serializer_class = SysOperLogSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = SysOperLogFilter
    ordering_fields = ['info_id']
    pagination_class = CustomPageNumberPagination


class SystemRoleViewSet(viewsets.ModelViewSet):
    '''
    系统角色视图级
    '''
    queryset = SystemRole.objects.all().order_by(F('role_id').asc())
    serializer_class = SystemRoleSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = SystemRoleFilter
    ordering_fields = ['role_id']
    pagination_class = CustomPageNumberPagination
    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['request'] = self.request
        return context



class ChangeRoleStatus(APIView):
    '''修改角色菜单状态'''

    def put(self, request):
        role_id = request.data['role_id']
        status = request.data['status']
        try:
            user_role = SystemRole.objects.get(role_id=role_id)
        except SystemRoleMenu.DoesNotExist:

            return {"errcode": 404, "mess": "用户id【%s】角色不存在" % role_id}
        user_role.status = status
        user_role.save()
        data = {"errcode": 200, "mess": "用户id【%s】角色状态修改成功" % role_id}
        return Response(data)


class RoleMenuTreeselect(APIView):
    '''
    根据角色ID查询菜单下拉树结构 和 已有菜单
    '''

    def get(self, request, userId):
        men = Menus(user_id=userId)

        data = {
            "checkedKeys": men.select_menu_list_by_role_id(),
            "menus": men._get_menu_treeselect()
        }
        return Response(data=data)


class MenuTreeSelect(APIView):
    '''
    菜单下拉树结构
    '''

    def get(self, request):
        men = Menus()
        data = men._get_menu_treeselect()
        return Response(data=data)


class UserMenuList(APIView):
    '''
    不同用户获取不同菜单
    '''
    # authentication_classes = (JSONWebTokenAuthentication,)


    def get(self, request):

        menusData = []

        login_user_info_view = LoginUserInfoView()
        login_user_response = login_user_info_view.get(request)

        if isinstance(login_user_response, Response):

            user_id = login_user_response.data.get('id')
        else:
            data = {"errcode": 404, "mess": "用户不存在"}
            return Response(data)
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            data = {"errcode": 404, "mess": "用户id【%s】不存在" % user_id}
            return Response(data)

        if user.is_superuser:
            main_menus = SystemMen.objects.filter(status=1, parentId=0).order_by('orderNum')
            for main_menu in main_menus:
                mainmenu = self.get_menu_data(main_menu)
                sub_menus = SystemMen.objects.filter(status=1, parentId=main_menu.menuId).order_by(
                    'orderNum')
                self.add_submenus(mainmenu, sub_menus)
                menusData.append(mainmenu)
            return Response(data=menusData)
        else:

            user_role = SystemUserRole.objects.filter(user_id=user.id).first()
            if not user_role:
                data = {"errcode": 404, "mess": "用户角色不存在请先创建角色"}
                return Response(data)
            else:
                u_role_id = user_role.role_id

            rolemens = SystemRoleMenu.objects.filter(role_id=u_role_id)
            men_ids = []
            for obj in rolemens:
                men_ids.append(obj.menu_id)



            main_menus = SystemMen.objects.filter(menuId__in=men_ids, status=1, parentId=0).order_by('orderNum')

            for main_menu in main_menus:
                mainmenu = self.get_menu_data(main_menu)
                sub_menus = SystemMen.objects.filter(menuId__in=men_ids, status=1, parentId=main_menu.menuId).order_by(
                    'orderNum')
                self.add_submenus(mainmenu, sub_menus)
                menusData.append(mainmenu)

            return Response(data=menusData)

    def get_menu_data(self, menu):
        menu_data = {
            'path': menu.path,
            'label': menu.menuName,
            'icon': menu.icon,
            'url': menu.component,
            'order_num': menu.orderNum
        }
        return menu_data

    def add_submenus(self, menu_data, sub_menus):
        if sub_menus.exists():
            menu_data['children'] = []
            for sub_menu in sub_menus:
                submenu_data = self.get_menu_data(sub_menu)
                submenu_children = SystemMen.objects.filter(status=1, parentId=sub_menu.menuId)
                if submenu_children.exists():
                    self.add_submenus(submenu_data, submenu_children)
                menu_data['children'].append(submenu_data)


class AllocatedList(viewsets.ViewSet):
    '''
    获取角色映射表中的用户信息
    '''

    def list(self, request):
        role_id = request.query_params.get('roleId')  # 从请求参数中获取角色ID
        username = request.query_params.get('username')
        mobile = request.query_params.get('mobile')
        user_role_instances = SystemUserRole.objects.filter(role_id=role_id)

        userlist = [user_role.user_id for user_role in user_role_instances]  # 从用户角色实例中提取用户信息

        if username is not None and mobile is not None:
            users = User.objects.filter(id__in=userlist).filter(username=username, mobile=mobile)
        elif mobile is not None:
            users = User.objects.filter(id__in=userlist).filter(mobile=mobile)
        elif username is not None:
            users = User.objects.filter(id__in=userlist).filter(username=username)
        else:
            users = User.objects.filter(id__in=userlist)

        serializer = UserSeralizer(users, many=True)  # 序列化用户信息
        data = {"rows": serializer.data, "total": len(serializer.data)}
        return Response(data)


class UnAllocatedList(viewsets.ViewSet):
    '''
    获取不在角色映射表中的用户信息
    '''

    def list(self, request):
        role_id = request.query_params.get('roleId')  # 从请求参数中获取角色ID
        username = request.query_params.get('username')
        mobile = request.query_params.get('mobile')
        user_role_instances = SystemUserRole.objects.filter(role_id=role_id)

        userlist = [user_role.user_id for user_role in user_role_instances]  # 从用户角色实例中提取用户信息

        if username is not None and mobile is not None:
            users = User.objects.exclude(id__in=userlist).filter(username=username, mobile=mobile)
        elif mobile is not None:
            users = User.objects.exclude(id__in=userlist).filter(mobile=mobile)
        elif username is not None:
            users = User.objects.exclude(id__in=userlist).filter(username=username)
        else:
            users = User.objects.exclude(id__in=userlist)

        serializer = UserSeralizer(users, many=True)  # 序列化用户信息
        data = {"rows": serializer.data, "total": len(serializer.data)}
        return Response(data)


class authUserSelectAll(APIView):
    '''
    添加用户到角色 映射表
    '''

    def put(self, request):

        roleId = request.data['roleId']
        userIds = str(request.data['userIds'])
        if ',' in userIds:
            userlist = str(userIds).split(',')
        else:
            userlist = userIds
        try:
            user_role = SystemRole.objects.get(role_id=roleId)
        except SystemRole.DoesNotExist:
            return {"errcode": 404, "mess": "用户id【%s】角色不存在" % roleId}

        for userid in userlist:
            SystemUserRole.objects.create(role_id=user_role.role_id, user_id=userid)
        data = {"errcode": 200, "mess": "用户id[%s]添加角色成功" % userIds}
        return Response(data)


class authUserCancelAll(APIView):
    '''
    从角色映射表中移除用户
    '''

    def put(self, request):

        roleId = request.data['roleId']
        userIds = str(request.data['userIds'])
        if ',' in userIds:
            userlist = str(userIds).split(',')
        else:
            userlist = userIds
        try:
            user_role = SystemRole.objects.get(role_id=roleId)
        except SystemRole.DoesNotExist:
            return {"errcode": 404, "mess": "用户id【%s】角色不存在" % roleId}

        for userid in userlist:
            SystemUserRole.objects.filter(role_id=user_role.role_id, user_id=userid).delete()
        data = {"errcode": 200, "mess": "删除用户id[%s]成功" % userIds}
        return Response(data)
